package netty.test20TcpMergeSpilt;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import javax.swing.*;
import java.util.UUID;

public class MyTcpClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    private int count=0;

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf msg) throws Exception {

        byte[] bytes = new byte[msg.readableBytes()];
        msg.readBytes(bytes);
        //将字节数组转换为字符串
        System.out.println("客户端端接收数据----》"+new String(bytes, CharsetUtil.UTF_8));

        System.out.println("客户端端读取的数据次数="+(++this.count));

    }

    //重写channelActive发送数据

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("11111111111MyClientHandler执行了");
        //使用客户端发送10次数据
        for(int i=0;i<10;i++){
            ByteBuf byteBuf = Unpooled.copiedBuffer("hello server " + i, CharsetUtil.UTF_8);
            ctx.writeAndFlush(byteBuf);
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
